package com.app.baselibrary.utils
import android.app.AlertDialog
import android.content.Context
import android.content.pm.PackageManager
import android.os.Build
import android.text.TextUtils
import android.widget.Toast
import androidx.core.content.ContextCompat
import com.app.baselibrary.ktx.ToastUtil
import com.hjq.permissions.OnPermissionCallback
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions

/**
@author: yangjie
@descruption: 权限申请工具类$
 */
class PermissionUtils {
    companion object {
        private val instance = PermissionUtils()

        /**
         * 获取单例
         */
        fun getInstance() = instance
    }

    /**
     * 定位权限
     */
     val LOCATIONPERMISSIONS = arrayOf(
        Permission.ACCESS_COARSE_LOCATION,
        Permission.ACCESS_FINE_LOCATION
    )

    /**
     * 视频通话权限
     */
     val VIDEORMISSIONS = arrayOf(
        Permission.RECORD_AUDIO,
        Permission.READ_MEDIA_VIDEO,
        Permission.READ_MEDIA_AUDIO,
        Permission.CAMERA,
        Permission.READ_MEDIA_IMAGES
    )


    //java.lang.IllegalArgumentException: When targetSdkVersion >= 33
    // should use android.permission.READ_MEDIA_IMAGES,
    // android.permission.READ_MEDIA_VIDEO,
    // android.permission.READ_MEDIA_AUDIO instead of
    // android.permission.READ_EXTERNAL_STORAGE,
    // android.permission.WRITE_EXTERNAL_STORAGE
    //

    /**
     * 相机存储权限
     */
     val PERMISSIONS = arrayOf(
        Permission.CAMERA,
        Permission.READ_MEDIA_IMAGES,
        Permission.READ_MEDIA_VIDEO,
        Permission.READ_MEDIA_AUDIO,
    )

    /**
     * 存储权限
     */
    val PERMISSION = arrayOf(
        Permission.READ_MEDIA_IMAGES,
        Permission.READ_MEDIA_VIDEO,
        Permission.READ_MEDIA_AUDIO,
    )
    /**
     * 判断定位权限是否开启
     */
    fun checkLocationPermission(ctx: Context): Boolean {
        return XXPermissions.isGranted(ctx, LOCATIONPERMISSIONS)
    }

    /**
     * 判断相机,存储权限
     */
    fun checkPermission(ctx: Context): Boolean {
        return XXPermissions.isGranted(ctx, PERMISSIONS)
    }


    fun checkVidePermission(ctx: Context): Boolean {
        return XXPermissions.isGranted(ctx, VIDEORMISSIONS)
    }

    fun requsetLocationPermission(
        mContext: Context,
        mActivityResultData: ActivityResultData
    ) {
        if (checkLocationPermission(mContext)) {
            mActivityResultData.onDataesult(200)
        } else {
            requestLocation(mContext, object :
                ActivityResultData {
                override fun onDataesult(code: Int) {
                    if (code == 200) {
                        mActivityResultData.onDataesult(200)
                    } else {
                        if (checkLocationPermission(mContext)) {
                            mActivityResultData.onDataesult(200)
                        } else {
                            mActivityResultData.onDataesult(code)
                        }
                    }
                }
            })
        }
    }

    /**
     * 视频通话申请权限
     *       Permission.CAMERA,
    Permission.READ_MEDIA_IMAGES,
    Permission.READ_MEDIA_VIDEO,
    Permission.READ_MEDIA_AUDIO,
     */
     fun requestVideo(
        mContext: Context,
        mActivityResultData: ActivityResultData
    ) {
        if (checkVidePermission(mContext)) {
            mActivityResultData.onDataesult(200)
        } else {
            XXPermissions.with(mContext)
                .permission(Permission.CAMERA)
                .permission(Permission.RECORD_AUDIO)
                .permission(Permission.READ_MEDIA_VIDEO)
                .permission(Permission.READ_MEDIA_AUDIO)
                .permission(Permission.READ_MEDIA_IMAGES)
                .request(
                    object : OnPermissionCallback {
                        override fun onGranted(permissions: List<String>, all: Boolean) {
                            if (all) {
                                //全部申请
                                mActivityResultData.onDataesult(200)
                            } else {
                                //获取部分权限成功，但部分权限未正常授予
                                mActivityResultData.onDataesult(100)
                            }
                        }

                        override fun onDenied(permissions: List<String>, never: Boolean) {
                            if (never) {
                                // 如果是被永久拒绝就跳转到应用权限系统设置页面
                                mActivityResultData.onDataesult(-1)
                            } else {
                                //权限取消或者失败
                                mActivityResultData.onDataesult(-2)
                            }
                        }
                    }
                )
        }
    }

    /**
     * 单独定位权限申请 类型 LOCATION
     */
    private fun requestLocation(
        mContext: Context,
        mActivityResultData: ActivityResultData
    ) {

            XXPermissions.with(mContext)
                .permission(Permission.ACCESS_COARSE_LOCATION)
                .permission(Permission.ACCESS_FINE_LOCATION)
                .request(
                    object : OnPermissionCallback {
                        override fun onGranted(permissions: List<String>, all: Boolean) {
                            if (all) {
                                //全部申请
                                mActivityResultData.onDataesult(200)
                            } else {
                                //获取部分权限成功，但部分权限未正常授予
                                mActivityResultData.onDataesult(100)
                            }
                        }

                        override fun onDenied(permissions: List<String>, never: Boolean) {
                            if (never) {
                                // 如果是被永久拒绝就跳转到应用权限系统设置页面
                                mActivityResultData.onDataesult(-1)
                            } else {
                                //权限取消或者失败
                                mActivityResultData.onDataesult(-2)
                            }
                        }
                    }
                )
    }

    /**
     * 类型 STORAGEORCAMRA 存储，相机
     * @param mContext
     * @param mActivityResultData
     */
    fun requestCameraPermissions(mContext: Context, mActivityResultData: ActivityResultData) {
            XXPermissions.with(mContext).permission(PERMISSIONS).request(
                object : OnPermissionCallback {
                    override fun onGranted(permissions: List<String>, all: Boolean) {
                        if (all) {
                            //全部申请
                            mActivityResultData.onDataesult(200)
                        } else {
                            //获取部分权限成功，但部分权限未正常授予
                            mActivityResultData.onDataesult(100)
                        }
                    }

                    override fun onDenied(permissions: List<String>, never: Boolean) {
                        if (never) {
                            // 如果是被永久拒绝就跳转到应用权限系统设置页面
                            mActivityResultData.onDataesult(-1)
                        } else {
                            //权限取消或者失败
                            mActivityResultData.onDataesult(-2)
                        }
                    }
                }
            )
    }


    /**
     * 存储权限
     */
    fun requestStargePermissions(mContext: Context, mActivityResultData: ActivityResultData) {
        XXPermissions.with(mContext).permission(PERMISSION).request(
            object : OnPermissionCallback {
                override fun onGranted(permissions: List<String>, all: Boolean) {
                    if (all) {
                        //全部申请
                        mActivityResultData.onDataesult(200)
                    } else {
                        //获取部分权限成功，但部分权限未正常授予
                        mActivityResultData.onDataesult(100)
                    }
                }

                override fun onDenied(permissions: List<String>, never: Boolean) {
                    if (never) {
                        // 如果是被永久拒绝就跳转到应用权限系统设置页面
                        mActivityResultData.onDataesult(-1)
                    } else {
                        //权限取消或者失败
                        mActivityResultData.onDataesult(-2)
                    }
                }
            }
        )
    }
    private fun verifyPermissions(permissions: List<String>, mContext: Context): String? {
        val stringBuffer = StringBuffer()
        try {
            for (result in permissions) {
                if (ContextCompat.checkSelfPermission(
                        mContext.applicationContext,
                        result
                    ) != PackageManager.PERMISSION_GRANTED
                ) {
                    //未授权
                    stringBuffer.append(getPermissionName(result))
                    stringBuffer.append("、")
                }
            }
        } catch (e: Throwable) {
            e.printStackTrace()
        }
        if (stringBuffer.isNotEmpty()) {
            stringBuffer.deleteCharAt(stringBuffer.length - 1)
        }
        return stringBuffer.toString()
    }

    private fun verifyPermissions(permissions: Array<String>, mContext: Context): String? {
        val stringBuffer = StringBuffer()
        try {
            for (result in permissions) {
                if (ContextCompat.checkSelfPermission(
                        mContext.applicationContext,
                        result
                    ) != PackageManager.PERMISSION_GRANTED
                ) {
                    //未授权
                    stringBuffer.append(getPermissionName(result))
                    stringBuffer.append("、")
                }
            }
        } catch (e: Throwable) {
            e.printStackTrace()
        }
        if (stringBuffer.isNotEmpty()) {
            stringBuffer.deleteCharAt(stringBuffer.length - 1)
        }
        return stringBuffer.toString()
    }

    private fun getPermissionName(permission: String): String? {
        var permissionName = ""
        permissionName = if (permission == Permission.CAMERA) {
            "相机权限"
        } else if (permission == Permission.READ_EXTERNAL_STORAGE || permission == Permission.WRITE_EXTERNAL_STORAGE) {
            "文件存储权限"
        } else if (permission == Permission.RECORD_AUDIO) {
            "录音权限"
        } else if (permission == Permission.ACCESS_COARSE_LOCATION || permission == Permission.ACCESS_FINE_LOCATION) {
            "定位权限"
        }else if (permission == Permission.POST_NOTIFICATIONS) {
            "通知栏权限"
        }else {
            "部分权限"
        }
        return permissionName
    }

    /**
     * 显示未授权的权限
     */

    fun  showPerDialog( mContext: Context,
                        code: Int,
                        permissions: Array<String>,
                        mActivityResultData: DialogResultData?=null){
        when (code) {
            100 -> {
                showNoPermissionDialog(mContext,permissions, mActivityResultData)
            }
            -1 -> {
                showJuJuePermissionDialog(mContext,permissions, mActivityResultData)
            }
            -2 -> {
                showCancelPermissionDialog(mContext,permissions, mActivityResultData)
            }
        }
    }
    private fun showNoPermissionDialog( mContext: Context,
                                permissions: Array<String>,
                                mActivityResultData: DialogResultData?=null){
        if (Build.VERSION.SDK_INT >= 23) {
            val perContent = verifyPermissions(permissions, mContext)
            if (perContent != null && !TextUtils.isEmpty(perContent)) {
                val message = """
                                应用${perContent}都未授权,对应用的功能将会受到影响。    
                                请点击"设置"-"权限"-打开所需权限。
                                """.trimIndent()
                showPermissionDialog(
                    message,
                    mContext,
                    permissions,
                    mActivityResultData
                )
            }
        }
    }

    /**
     * 显示拒绝权限窗口
     */
   private fun showJuJuePermissionDialog( mContext: Context,
                                   permissions: Array<String>,
                                   mActivityResultData: DialogResultData?=null){
        // 如果是被永久拒绝就跳转到应用权限系统设置页面
        if (Build.VERSION.SDK_INT >= 23) {
            val message = "您已拒绝" + verifyPermissions(
                permissions,
                mContext
            ) + ",对应用功能的将会受到影响。\n\n请点击\"设置\"-\"权限\"-打开所需权限。"
            showPermissionDialog(
                message,
                mContext,
                permissions,
                mActivityResultData
            )
        }
    }
     /**
     * 显示取消权限窗口
     */
     private fun showCancelPermissionDialog( mContext: Context,
                                     permissions: Array<String>,
                                     mActivityResultData: DialogResultData?=null) {
         if (Build.VERSION.SDK_INT >= 23) {
             val message = "您已取消" + verifyPermissions(
                 permissions,
                 mContext
             ) + ",对应用功能的将会受到影响。\n\n请点击\"设置\"-\"权限\"-打开所需权限。"
             showPermissionDialog(
                 message,
                 mContext,
                 permissions,
                 mActivityResultData
             )
         }
     }
    /**
     * 显示未授权权限提示信息
     *
     */
    private var builder: AlertDialog.Builder? = null

    private  fun showMissingPermissionDialog(
        message: String,
        typeId: String,
        permissions: List<String>,
        mContext: Context
    ) {
//        if (isShowPermissionDialog) {
            try {
                if (builder == null) {
                    builder = AlertDialog.Builder(mContext)
                }
                builder!!.setTitle("提示")
                builder!!.setMessage(message)
                // 拒绝, 退出应用
                builder!!.setNegativeButton(
                    "取消"
                ) { dialog, which ->
                    try {
                        ToastUtil.show("您已取消权限设置，部分功能使用将会收到影响！！！", Toast.LENGTH_LONG)
//                        isShowPermissionDialog = false
                        builder = null
                    } catch (e: Throwable) {
                        e.printStackTrace()
                    }
                }
                builder!!.setPositiveButton(
                    "设置"
                ) { dialog, which ->
                    try {
                        //开启设置
                        XXPermissions.startPermissionActivity(mContext, permissions)
                        builder = null
                    } catch (e: Throwable) {
                        e.printStackTrace()
                    }
                }
                builder!!.setCancelable(false)
                if (builder != null && !builder!!.show().isShowing) {
                    builder!!.show()
                }
            } catch (e: Throwable) {
                e.printStackTrace()
            }
//        }
    }

    private fun showPermissionDialog(
         message: String,
         mContext: Context,
         permissions: Array<String>,
         mActivityResultData: DialogResultData?=null
    ) {
        try {
            if (builder == null) {
                builder = AlertDialog.Builder(mContext)
            }
            builder!!.setTitle("提示")
            builder!!.setMessage(message)
            // 拒绝, 退出应用
            builder!!.setNegativeButton(
                "取消"
            ) { dialog, which ->
                try {
                    ToastUtil.show("您已取消权限设置，部分功能使用将会收到影响！！！", Toast.LENGTH_LONG)
                    builder = null
                    mActivityResultData?.onDialogWindow(101)
                } catch (e: Throwable) {
                    e.printStackTrace()
                }
            }
            builder!!.setPositiveButton(
                "设置"
            ) { dialog, which ->
                try {
                    //开启设置
                    XXPermissions.startPermissionActivity(mContext, permissions)
                    mActivityResultData?.onDialogWindow(100)
                    builder = null
                } catch (e: Throwable) {
                    e.printStackTrace()
                }
            }
            builder!!.setCancelable(false)
            if (builder != null && !builder!!.show().isShowing) {
                builder!!.show()
            }
        } catch (e: Throwable) {
            e.printStackTrace()
        }
    }

    /**
     * android  13 通知栏权限判断
     */
     val NOTICEPERMISSIONS = arrayOf(
        Permission.POST_NOTIFICATIONS,
//        Permission.NOTIFICATION_SERVICE //直接调用到的通知栏权限界面
    )

    fun requestNoticePermissions(mContext: Context, mActivityResultData: ActivityResultData) {
         if(XXPermissions.isGranted(mContext,NOTICEPERMISSIONS)){
             mActivityResultData.onDataesult(200)
         }else{
             XXPermissions.with(mContext).permission(NOTICEPERMISSIONS).request(
                 object : OnPermissionCallback {
                     override fun onGranted(permissions: List<String>, all: Boolean) {
                         if (all) {
                             //全部申请
                             mActivityResultData.onDataesult(200)
                         } else {
                             //获取部分权限成功，但部分权限未正常授予
                             mActivityResultData.onDataesult(100)
                         }
                     }

                     override fun onDenied(permissions: List<String>, never: Boolean) {
                         if (never) {
                             // 如果是被永久拒绝就跳转到应用权限系统设置页面
                             mActivityResultData.onDataesult(-1)
                         } else {
                             //权限取消或者失败
                             mActivityResultData.onDataesult(-2)
                         }
                     }
                 }
             )
         }
    }
    interface ActivityResultData {

        fun onDataesult(code: Int)

    }

    interface DialogResultData{
        fun onDialogWindow(code: Int)
    }
}